package com.ucap.wsbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.ucap.spyxmp.data.RestResultBuilder;
import com.ucap.spyxmp.data.ResultModel;
import com.ucap.spyxmp.util.CommonUtil;
import com.ucap.util.*;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;


public class ThirdDataController  extends Controller {
    private static String CONTENT_TYPE_JSON = "application/json";
    private static String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";

    public void getXkzLogin(){

        String url="http://19.104.11.123:8086/api/json/publicService";
        JSONObject param = new JSONObject();
        param.put("sessionId","xzspgl");
        param.put("serviceId","xzspgl");
        param.put("taskId","0");
        param.put("encryptKey","cd30ef7a5594fd6d6e0c2f2393bdcd8c");
        param.put("username","liangjin");
        param.put("password","337223");

        String signature=null;
        String contentType="application/json";
        String result= HttpRequest.sendPost(url,param.toString(),signature,contentType);
        System.out.println(result);
    }

    /**
     * 许可证查询
     */
    public void getXkzInfo(){

        if(PropKit.getBoolean("thirdIsLocal")){
            JSONObject data = new JSONObject();
            data.put("qymc", "东莞测试公司");
            renderJson(RestResultBuilder.builder().success().data(data).build());
        }else{
            String classifyId=getPara("classifyId");
            String certNo= PropKit.get("certNo") != null ? PropKit.get("certNo") : getPara("certNo");
            ResultModel<JSONObject> licenseDataResultModel = CommonUtil.getLicenseData(classifyId, certNo);
            //如果有数据，将数据存入session
            if(licenseDataResultModel.getSuccess() && licenseDataResultModel.getData() != null){
                if("GSP".equals(classifyId)){
                    this.getSession().setAttribute(CommonUtil.LICENSE_DATA_GSP, licenseDataResultModel.getData());
                }else{
                    this.getSession().setAttribute(CommonUtil.LICENSE_DATA, licenseDataResultModel.getData());
                }
            }
            renderJson(licenseDataResultModel);
        }
    }


    public static void main(String[] args) {

        String templatePath = "E:/myproject/dgdcwx/src/main/webapp/files/template/spjyxkz/zxjds.pdf";
        //生成的新文件路径
        String newPDFPath = "E:/myproject/dgdcwx/src/main/webapp/files/license/xkz" + DateUtil.getSdfTimes() + ".pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            FileUtil.copyFile(templatePath, newPDFPath);

            out = new FileOutputStream(newPDFPath);//输出流
            reader = new PdfReader(templatePath);//读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //使用中文字体
            BaseFont bf = BaseFont.createFont("E:/myproject/dgdcwx/src/main/webapp/fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //BaseFont bf = BaseFont.createFont("E:/myproject/dgdcwx/src/main/webapp/fonts/simsun.ttc", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            //BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(bf);
            form.setSubstitutionFonts(fontList);
            String str = "{\"xkzbh\":\"JY24419180000470\",\"fzjg\":\"东莞市食品药品监督管理局\",\"yxqn\":\"\",\"ztyt\":\"（网络经营）\",\"jycs\":\"东莞市东城区\",\"qfrqy\":\"\",\"tyshxydm\":\"441323197212206330\",\"jyzmc\":\"东莞市东城鱼满塘餐厅\",\"rcjdgljg\":\"\",\"qfrqn\":\"\",\"rcjdglry\":\"\",\"qfrqr\":\"\",\"yxqr\":\"\",\"qfr\":\"\",\"yxqy\":\"\"}";

            JSONObject dataJson = JSONObject.parseObject(str);
            int i = 0;
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while(it.hasNext()){
                String name = it.next().toString();
                System.out.print(name);
                System.out.print("=====");
                System.out.println(dataJson.getString(name));
                form.setField(name, "181229004");
            }
            stamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(
                    new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(1);
        } catch (DocumentException e) {
            e.printStackTrace();
            System.out.println(2);
        }


        PDF2IMAGE.pdf2Image(newPDFPath, "E:/myproject/dgdcwx/src/main/webapp/files/license/", 100);

    }
}
